package com.blb.gatewayservice.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/**
 * 全局Token验证的过滤器
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    /**
     * 过滤
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得token参数
        String token = request.getQueryParams().getFirst("token");
        //验证token，成功就放行
        if("123456".equals(token)){
            return chain.filter(exchange);
        }
        //设置401响应码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //保证响应信息
        DataBuffer wrap = response.bufferFactory().wrap("Login Failed".getBytes());
        //返回数据给客户端
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        // 值越大，过滤器执行越靠后
        return 0;
    }
}
